package study.sparsearray;

public class SparseArray {
    public static void main(String[] args) {
        //创建一个原始的二维数组
        int[][] arr1 = new int[11][11];
        arr1[1][2] = 5;
        arr1[2][3] = 7;


        //输出原始的数组
        System.out.println("原始的数组:");
        for (int[] row : arr1) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }

        //统计原始数组中非0数据的个数
        int sum = 0;
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr1[i].length; j++) {
                if (arr1[i][j] != 0) {
                    sum++;
                }
            }
        }
        System.out.println("sum = " + sum);

        //创建稀疏数组
        // 因为第一行存放的数“统计”原始数组的数据，第二行开始才是存放索引与值，所以行号要+1
        int[][] sparseArray = new int[sum + 1][3];
        //给稀疏数组赋值
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;

        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (arr1[i][j] != 0) {
                    count++;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = arr1[i][j];
                }
            }
        }

        //输出二维数组
        System.out.println("输出稀疏二维数组");
        for (int[] row : sparseArray) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }

        //恢复成原始二维数组
        int[][] arr2 = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i < sparseArray.length; i++) {
            arr2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }

        //输出恢复的二维数组
        System.out.println("输出恢复的二维数组");
        for (int[] row : arr2) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}
